package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.feign.WmUserFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.ApUserRealnameMapper;
import com.usian.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl  extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService{

    @Override
    public PageResponseResult loadListByStatus(AuthDto authDto) {
        if (authDto==null){
            return (PageResponseResult) ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检出参数
        authDto.checkParam();
        QueryWrapper<ApUserRealname> queryWrapper = new QueryWrapper<>();
        if (authDto.getStatus()!=null){
            queryWrapper.lambda().eq(ApUserRealname::getStatus,authDto.getStatus());
        }
        IPage pageParam = new Page(authDto.getPage(),authDto.getSize());
        IPage page = page(pageParam, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(authDto.getPage(),authDto.getSize(),(int)page.getTotal());
        responseResult.setCode(0);
            responseResult.setData(page.getRecords());
        return responseResult;
    }


    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApUserMapper  apUserMapper;


    public static final Short PASS_AUTH = 9; //审核通过
    public static final Short FAIL_AUTH = 2; //审核不通过
    public static final Short AUTHOR_TYPE = 2; //平台自媒体人

    /**
     * 用户认证审核业务
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional //管理事务
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        //校验参数
        if (dto == null || dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(this.statusCheck(status)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //更新审核状态 1：跟新ApUserRealname
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (dto.getMsg() != null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //通过 --》wmuser(realname--userid---apuser---) ---》apauthor---》update  ap_user_realname  ---》update  apuser  flag

        if(status.equals(PASS_AUTH)){
            //2创建自媒体账号
            ResponseResult responseResult = createWmUserAndAuthor(dto);


        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private ResponseResult createWmUserAndAuthor(AuthDto dto){
        ApUserRealname userrealname = this.getById(dto.getId());
        ApUser apUser = apUserMapper.selectById(userrealname.getUserId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断 wmuser 是否有账号
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        if(wmUser==null){
            wmUser = new WmUser();
            //设置ApUserId
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setStatus(Integer.valueOf(PASS_AUTH));   //标记审核通过
            wmUser.setPhone(apUser.getPhone());
            wmUserFeign.add(wmUser);
        }


        //3：写入作者表
        createAuthor(wmUser);

        apUser.setFlag((short) 1); //1 自媒体人
        apUserMapper.updateById(apUser);

        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor =  articleFeign.findByUserId(apUserId);
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType((int)AUTHOR_TYPE);
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            apAuthor.setWmUserId(wmUser.getId());
            articleFeign.add(apAuthor);
        }
    }

    private boolean statusCheck(Short status) {
        if (status == null
                || ( !status.equals(FAIL_AUTH)&& !status.equals(PASS_AUTH))) {
            return true;  // status ==null   status =4,5,7,8     9,2   true:参数不合格
        }
        return false; //参数合格
    }
}
